package lowijs.XfireClient.packet;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import lowijs.XfDroid.FriendDBAdapter;

public class LoginReplyPacket extends Packet {
	private int userid;
	private byte[] sid = new byte[16];
	private int status;
	private String nickname;
	
	public LoginReplyPacket(byte[] data, String username) {
		ByteBuffer buffer = ByteBuffer.wrap(data);
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		userid = buffer.getInt(11);
		System.arraycopy(data, 20, sid, 0, 16);
		
		int namelengthLen = data[41] & 0xFF;
		int nameLen = 0, startbyte = 0;
		if (namelengthLen == 1) {
			nameLen = data[42] & 0xFF;
			startbyte = 44;
		} else {
			nameLen = fromLowHigh(data[42], data[43]);
			startbyte = 45;
		}
		
		if (data[startbyte] != 0) {
			byte[] nameBytes = new byte[nameLen];
			System.arraycopy(data, startbyte, nameBytes, 0, nameLen);
			nickname = new String(nameBytes);
		} else {
			nickname = "";
		}
		
		//startbyte += nameLen + 8;
		//System.arraycopy(data, startbyte, status, 0, 4);

		FriendDBAdapter db = FriendDBAdapter.getInstance(null);
		db.login(userid, username, nickname, sid);
	}
	
	public int getUserId() {
		return userid;
	}
	
	public byte[] getSid() {
		return sid;
	}
	
	public String getNickname() {
		return nickname;
	}
	
	public int getStatus() {
		return status;
	}
}
